package com.example.aspect;

import com.example.common.BusinessError;
import com.example.common.CommonError;
import com.example.common.CommonRes;
import com.example.common.Constants;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 * 全局异常处理
 * @author: jimmy
 * @date: 2023年12月25日 14:41
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest servletRequest, HttpServletResponse httpServletResponse, Exception ex) {
        ex.printStackTrace();



        //参数校验错误
        if (ex instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult =((MethodArgumentNotValidException)ex).getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<String> errList = new ArrayList<>();
            for (ObjectError allError : allErrors) {
                errList.add(allError.getDefaultMessage());
            }
            if (errList.size() > 0) {
                CommonError commonError = new CommonError(Constants.CODE_10005, errList);
                return CommonRes.createError(commonError);
            }
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        } else if (ex instanceof InsufficientAuthenticationException || ex instanceof AccessDeniedException) {
            //没有权限或token过期
            CommonError commonError = new CommonError(BusinessError.ACCESS_DENIED_ERROR);
            return CommonRes.createError(commonError);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }

    }
}
